Repository navigation
serve: reasoning as thinking blocks on the Messages API (and reasoning_content with tool calls) - #135
PedroRossi wants to merge 3 commits into
Conversation
🔍 Aletheore evidence diffgraph LR
n0["src/serve.rs"]
n1["src/chat.rs"]
n2["src/deepseek/chat.rs"]
n3["src/gemma4/mod.rs"]
n4["src/glm/mod.rs"]
n5["grammar.rs"]
n6["hf.rs"]
n7["src/hy4/chat.rs"]
n8["src/inkling2/chat.rs"]
n9["src/kolibri/chat.rs"]
n10["lib.rs"]
n11["src/raon/chat.rs"]
n12["tests/serve.rs"]
n13["tokenizer.rs"]
n0 --> n1
n0 --> n2
n0 --> n3
n0 --> n4
n0 --> n5
n0 --> n6
n0 --> n7
n0 --> n8
n0 --> n9
n0 --> n10
n0 --> n11
n0 --> n12
n0 --> n13
classDef changed fill:#d9772c,color:#fff,stroke:#b85f1c;
classDef changedFinding fill:#c0392b,color:#fff,stroke:#922b21;
classDef dependent fill:#f2f0ec,color:#18140f,stroke:#d6d0c5;
class n0 changed
class n1 dependent
class n2 dependent
class n3 dependent
class n4 dependent
class n5 dependent
class n6 dependent
class n7 dependent
class n8 dependent
class n9 dependent
class n10 dependent
class n11 dependent
class n12 dependent
class n13 dependent
What changed
Aggregate deltas
|
| if t.is_empty() { return Ok(()); } | ||
| if self.open != Some(thinking) { | ||
| self.close(w)?; | ||
| let block = if thinking { json!({"type": "thinking", "thinking": ""}) } else { json!({"type": "text", "text": ""}) }; |
There was a problem hiding this comment.
✅ No longer detected as of c2db2f5e7b1c.
🟠 High · Correctness · 1 of 4
Thinking content_block_start omits the signature field that the non-streaming thinking block includes. The non-streaming path emits a thinking block with "signature": "", but the streaming content_block_start emits {"type":"thinking","thinking":""}. A strict Anthropic-style client that builds the block from the start event and then sees signature_delta may hit a missing-field error or assemble a different shape than the non-streaming reply.
Prompt for your AI agent
File: src/main.rs
Line: 3964
Symbol: handle
Issue: Thinking content_block_start omits the signature field that the non-streaming thinking block includes. The non-streaming path emits a thinking block with "signature": "", but the streaming content_block_start emits {"type":"thinking","thinking":""}. A strict Anthropic-style client that builds the block from the start event and then sees signature_delta may hit a missing-field error or assemble a different shape than the non-streaming reply.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.
There was a problem hiding this comment.
Fixed in dab867e. A streamed thinking block now starts with "signature": "", the same shape as a whole reply's block, and the signature_delta still comes before it stops. The stream test checks the start block.
| self.send(w, p) | ||
| } | ||
| /// Sends `rest` and what the splitter still holds, then stops the open block. | ||
| fn finish(&mut self, w: &mut impl Write, rest: &str) -> anyhow::Result<()> { |
There was a problem hiding this comment.
✅ No longer detected as of dab867ec231d.
🔵 Low · Maintainability · 2 of 4
AnthStream::finish re-implements the split_think feed/finish sequence instead of reusing it. The Think feed-then-finish sequence now lives in split_think, in AnthStream::finish, and in AnthStream::feed/send. A later change to how Think flushes held text (for example a partial </think> at end of stream) must be made in several places, and one copy can drift from the others.
Prompt for your AI agent
File: src/main.rs
Line: 3949
Symbol: handle
Issue: AnthStream::finish re-implements the split_think feed/finish sequence instead of reusing it. The Think feed-then-finish sequence now lives in split_think, in AnthStream::finish, and in AnthStream::feed/send. A later change to how Think flushes held text (for example a partial </think> at end of stream) must be made in several places, and one copy can drift from the others.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.
There was a problem hiding this comment.
Fixed in dab867e: finish now calls feed, then flushes the splitter.
| if stream { return json!({"tool_calls": c}); } | ||
| // The text before the calls opens with the reasoning when the prompt ended in an open think block. | ||
| let (r, a) = split_think(think_open, content); | ||
| let mut m = json!({"role": "assistant", "content": if a.is_empty() { None } else { Some(a) }, "tool_calls": c}); |
There was a problem hiding this comment.
✅ No longer detected as of c2db2f5e7b1c.
🔵 Low · Maintainability · 3 of 4
Early return inside the calls_json branch makes the tool-call message shape hard to follow. The stream and non-stream outcomes are built in one expression with a return on one arm and a trailing expression on the other. A reader or a later edit can miss that the streamed tool-call message silently drops reasoning, and a change to the non-stream fields may not reach the streamed path.
Prompt for your AI agent
File: src/main.rs
Line: 4342
Issue: Early return inside the calls_json branch makes the tool-call message shape hard to follow. The stream and non-stream outcomes are built in one expression with a return on one arm and a trailing expression on the other. A reader or a later edit can miss that the streamed tool-call message silently drops reasoning, and a change to the non-stream fields may not reach the streamed path.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.
There was a problem hiding this comment.
Restructured in dab867e as one if/else. On the streamed path the reasoning isn't dropped, though: it goes out earlier, as reasoning_content deltas before the tool-call deltas.
| /// has none to give), then the answer as a `text` block, then the tool calls. | ||
| fn anthropic_content(reasoning: &str, text: &str, uses: Vec<serde_json::Value>) -> Vec<serde_json::Value> { | ||
| let thinking = (!reasoning.is_empty()).then(|| json!({"type": "thinking", "thinking": reasoning, "signature": ""})); | ||
| let text = (!text.is_empty()).then(|| json!({"type": "text", "text": text})); |
There was a problem hiding this comment.
✅ No longer detected as of dab867ec231d.
🟡 Medium · Correctness · 4 of 4
Non-streaming reply with reasoning but no text or tool calls returns only a thinking block. A reply that is all reasoning (for example one cut off by max_tokens before </think>) yields content with only a thinking block. Clients that read content[0].text, or expect a text block as the final answer, get nothing usable and may treat the reply as empty.
Prompt for your AI agent
File: src/main.rs
Line: 3932
Symbol: anthropic_refused
Issue: Non-streaming reply with reasoning but no text or tool calls returns only a thinking block. A reply that is all reasoning (for example one cut off by max_tokens before </think>) yields content with only a thinking block. Clients that read content[0].text, or expect a text block as the final answer, get nothing usable and may treat the reply as empty.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.
There was a problem hiding this comment.
/dismiss By design. A reply cut off by max_tokens inside the reasoning has no answer, and the Messages API says exactly that: a thinking block alone, with stop_reason: "max_tokens". Anthropic's API does the same, and llama.cpp's server builds the same blocks. An empty text block would be a shape the API never sends.
Aletheore Flash Lite reviewWhat this PR does. This PR returns the model's reasoning separately from its answer: as
1 finding(s) posted as inline review comment(s). 4 earlier finding(s) no longer detected in this push.
Review detailsReviewed 3 file(s); skipped 0. Dismissed 0; outside PR diff 2. Grounding: 3 of 3 proposed finding(s). Fix all with your agentBlast radius: 63 other file(s) depend on what this PR changes (13 directly, 50 indirectly)Computed from the import graph of this exact commit, not guessed by a model. It sees imports only, so dynamic imports, reflection and non-code references are not counted.
Indirectly affected: The graph is large; this list is capped and not exhaustive. |
/v1/messages sent the whole generated text as one text block, so a thinking model's
reasoning and its </think> tag reached the client as the answer (Claude Code shows
it in every reply). It now goes through the same splitter as /v1/chat/completions:
- a whole reply: a thinking block (empty signature), then the text block, then the
tool_use blocks;
- a stream: a thinking block of thinking_delta pieces that stops after an empty
signature_delta, then the text block; the tool_use blocks take the indexes after.
thinking: {"type": "disabled"} now turns thinking off for the request; before, the
server default applied. Tests for the stream events, the whole-reply blocks and the
request mapping.
A non-streamed /v1/chat/completions reply with tool calls put the text before the calls in content as it was, reasoning and </think> included, with no reasoning_content. It now splits that text like a reply without calls. Streamed replies already split it.
- A streamed thinking block starts with an empty signature, the same shape as a whole reply's block (the signature_delta still comes before it stops); tested. - AnthStream::finish reuses feed instead of repeating it. - The tool-call message is one if/else: a stream's tool calls, or a whole reply's message with reasoning_content. No change in behaviour.
| b.finish(&mut out, "").unwrap(); | ||
| assert_eq!(events(&out), ["start 0 thinking", r#"0 thinking "Let me""#, r#"0 thinking " think.\n""#, r#"0 signature_delta """#, | ||
| "stop 0", "start 1 text", r#"1 text "The answer""#, r#"1 text " is 4.""#, "stop 1"]); | ||
| assert_eq!(b.next, 2); // a tool call would be block 2 |
There was a problem hiding this comment.
✅ No longer detected as of dab867ec231d.
🔵 Low · Maintainability · 1 of 2
The new test reads the first data: line, which is probably message_start, not the thinking content_block_start. The stream begins with message_start, so find_map returns that event. Its content_block is null and the assertion fails even when the thinking block is correct. The test should select the content_block_start event for index 0, or the thinking block's event, by its type field.
Prompt for your AI agent
File: src/main.rs
Line: 4432
Symbol: vram_margins_reject_bad_specs
Issue: The new test reads the first `data:` line, which is probably message_start, not the thinking content_block_start. The stream begins with message_start, so `find_map` returns that event. Its `content_block` is null and the assertion fails even when the thinking block is correct. The test should select the content_block_start event for index 0, or the thinking block's event, by its `type` field.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.
| else { json!({"role": "assistant", "content": if content.is_empty() { None } else { Some(content) }, "tool_calls": c}) } | ||
| if stream { | ||
| // A stream sent the reasoning already, as `reasoning_content` deltas before the calls. | ||
| json!({"tool_calls": c}) |
There was a problem hiding this comment.
✅ No longer detected as of dab867ec231d.
🔵 Low · Correctness · 2 of 2
The streaming tool-call branch relies on reasoning already having been sent as reasoning_content deltas, which the diff does not show. If the streaming path does not emit reasoning_content deltas before tool calls, the reasoning is dropped for streamed tool-call replies, while the non-streamed branch still returns it. The stream and non-stream outputs would then differ silently.
Prompt for your AI agent
File: src/main.rs
Line: 4341
Issue: The streaming tool-call branch relies on reasoning already having been sent as reasoning_content deltas, which the diff does not show. If the streaming path does not emit reasoning_content deltas before tool calls, the reasoning is dropped for streamed tool-call replies, while the non-streamed branch still returns it. The stream and non-stream outputs would then differ silently.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.
c2db2f5 to
dab867e
Compare
…ustingStudio#135 (Messages API thinking blocks) Integration branch for the ai-lab stack image; not for upstream.
| out.push(("thinking_budget", j.get("thinking").get("budget_tokens").clone())); | ||
| match j.get("thinking").get("type").as_str() { | ||
| Some("enabled") => { | ||
| out.push(("chat_template_kwargs", obj(vec![("enable_thinking", Json::Bool(true))]))); |
There was a problem hiding this comment.
🟠 High · Correctness · 1 of 1
thinking disabled sets enable_thinking false, but the model still writes a short think block, which then leaks into the answer The docs say Inkling 2 still writes a short thinking block at effort 0, even with enable_thinking false. A Messages request with thinking {"type":"disabled"} therefore gets a reply that opens with reasoning and a literal </think>. The caller builds Think::new(think_open) with think_open false, so nothing is split: the reasoning and the tag land in the text block. That is the leak this PR is meant to fix, and it returns for exactly the requests that asked to turn thinking off.
Prompt for your AI agent
File: src/serve.rs
Line: 946
Symbol: messages_body
Issue: thinking disabled sets enable_thinking false, but the model still writes a short think block, which then leaks into the answer The docs say Inkling 2 still writes a short thinking block at effort 0, even with enable_thinking false. A Messages request with thinking {"type":"disabled"} therefore gets a reply that opens with reasoning and a literal </think>. The caller builds Think::new(think_open) with think_open false, so nothing is split: the reasoning and the tag land in the text block. That is the leak this PR is meant to fix, and it returns for exactly the requests that asked to turn thinking off.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.
Summary
Independent of #134 (no shared files).
With a thinking model (Qwen3.5/3.6 with thinking on, the server default), the reasoning reaches some API clients mixed
into the answer.
/v1/messages(Anthropic Messages API, what Claude Code uses):textblock holding everything the model generated: reasoning, a literal</think>, then the answer.text_deltas of block 0, the same mix.thinking: {"type": "disabled"}: was ignored, so the server default applied and a client could not turn thinking off./v1/chat/completionsreplies that end in tool calls, not streamed: the text before the calls went tocontentas it was (reasoning and
</think>included), with noreasoning_content./v1/chat/completionsalready split the reasoning everywhere else withchat::Think. This PR uses the same splitterfor the cases above. The block layout and the empty signature follow what llama.cpp's server sends, which Claude Code
accepts.
thinkingblock ("signature": ""; a local model has no signature to give), then thetextblock, then thetool_useblocks.thinkingblock ofthinking_deltapieces. It starts with an empty signature, thesame shape as a whole reply's block, and stops after an empty
signature_delta, which the API requires before athinking block stops. Then comes the
textblock, and thetool_useblocks take the indexes after.</think>split over two pieces waits for the second, as on the OpenAI path.thinking: {"type": "disabled"}maps toenable_thinking: false;enabledwithbudget_tokensworks as before.reasoning_contentand a cleancontent(second commit, whichcan be dropped on its own).
split_thinkreplaces the inline split of the non-streamed OpenAI reply; behaviour there is unchanged.Without a think block (thinking off, or a model without one), the output is the same as before: one text block.
Before / after
POST /v1/messages, "What is 17*23? Answer with the number only.", Qwen3.6-35B-A3B, thinking on (server default):Tests
messages_api_tests(main.rs), which checks the exact event sequence of a stream:streamed_reasoning_is_a_thinking_block_before_the_textstreamed_reply_without_think_block_is_one_text_blockreasoning_cut_off_by_max_tokens_still_stops_its_blockwhole_reply_puts_reasoning_in_a_thinking_blockserve::messages_tests::thinking_turns_thinking_on_and_offmessages_api_requestpasses too.cargo test --releasein a container with NVRTC 12.4 and no GPU, so the GPU and model tests skip themselves.It gives 429 passed, 0 failed, 11 ignored (upstream's
#[ignore]speed tests)./v1/messages, whole:[thinking (1062 chars, signature ""), text "391"],end_turn, no</think>in the text./v1/messages, streamed:message_start,start 0 thinking,thinking_delta…,signature_delta,stop 0,start 1 text,text_delta…,stop 1,message_delta,message_stop.thinking: {"type": "disabled"}:[text "391"], no thinking block.[thinking, tool_use read_file],stop_reason: tool_use.tool_useblock 1 (input_json_delta)./v1/chat/completionswith a tool, whole:tool_calls [read_file],reasoning_content128 chars,contentempty(before: the reasoning and
</think>incontent)./v1/chat/completions, streamed) unchanged.